/*
 * Copyright 2011-2012 Redia A/S
 * 
 * This file is part of Redias Library App for Android.
 *
 *  Redia Library App for Android is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Redia Library App for Android is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with Redia Library App for Android.  If not, see <http://www.gnu.org/licenses/>.
 */
package dk.redia.libraryapp;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.Timer;
import java.util.TimerTask;

import com.google.android.apps.analytics.GoogleAnalyticsTracker;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Bundle;
import dk.redia.lib.log.Log;
import android.text.Html;
import android.text.Spanned;
import android.text.SpannedString;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import dk.redia.lib.model.InfoGalleriModel;
import dk.redia.lib.model.InfoObject;
import dk.redia.lib.model.Media;
import dk.redia.lib.net.ImageCache;
import dk.redia.lib.utils.AppApplication;
import dk.redia.lib.utils.AppConfiguration;
import dk.redia.lib.utils.UIUtils;
import dk.redia.libraryapp.activityutils.LibraryAppActivity;
import dk.redia.libraryapp.utils.ResourceUtils;
import dk.redia.libraryapp.viewutils.ViewUtils;

public class FrontPageActivity extends LibraryAppActivity implements Observer {

	private ProgressDialog progressDialog;
	
	private static final String logTag = "FrontPageActivity";
	private Timer tripleTapTimer;
	private int tapCounter;
	private long tapInterval = 1000;

	//private GoogleAnalyticsTracker tracker;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    
        //tracker = GoogleAnalyticsTracker.getInstance();
        //tracker.startNewSession("UA-34254449-1", 20, this);
        //tracker.trackPageView("/news"); 
	    
	    setContentView(R.layout.frontpage);
	    
	    // Easter egg access to development web service
	    tripleTapTimer = new Timer();
	    tapCounter = 0;
	    View v = findViewById(R.id.frontpageWideLogoImageView); 
	    if (v!=null) {
		    v.setOnTouchListener(new View.OnTouchListener() {
				
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					if (event.getAction()!=MotionEvent.ACTION_DOWN) {
						return false;
					}
					Log.d(logTag, "Logo touched");
					tapCounter++;
					if (tripleTapTimer!=null) {
						tripleTapTimer.cancel();	
					}
					Log.d(logTag, "Tap counter is " + tapCounter);
					if (tapCounter>2) {
						tapCounter = 0;
						AlertDialog.Builder alert = new AlertDialog.Builder(FrontPageActivity.this);
						final EditText pwField = new EditText(FrontPageActivity.this);
						alert.setView(pwField);
						alert.setTitle("Enter password");
						alert.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								
							}
						});
						
						alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								if (!pwField.getText().toString().equals("abc123")) {
									return;
								}
								boolean currentlyInProdMode = AppConfiguration.getInstance().getProductionMode();
								if (currentlyInProdMode) {
									Log.d(logTag, "Switching to test mode");
									Toast.makeText(FrontPageActivity.this, "Switching to test mode", Toast.LENGTH_SHORT).show();						
									AppConfiguration.getInstance().setProductionMode(false);
								} else {
									Log.d(logTag, "Switching to prod mode");
									Toast.makeText(FrontPageActivity.this, "Switching to prod mode", Toast.LENGTH_SHORT).show();						
									AppConfiguration.getInstance().setProductionMode(true);							
								}
								
							}
						});
						alert.show();

					} else {
						tripleTapTimer = new Timer();
						tripleTapTimer.schedule(new TimerTask() {						
							@Override
							public void run() {
								runOnUiThread(new Runnable() {								
									@Override
									public void run() {
										tapCounter = 0;	
										Log.d(logTag, "Cleared touch event counter");										
									}
								});						
							}
						}, tapInterval);
					}				
					return true;
				}
			});
	    }
	    
	    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	    ImageView wideLogoImageView = (ImageView)findViewById(R.id.frontpageWideLogoImageView);
	    wideLogoImageView.setImageResource(ResourceUtils.getWideLogoResourceId());
	    InfoGalleriModel.getInstance().addInfoObjectsObserver(this);
	    progressDialog = ProgressDialog.show(
	    		this, 
	    		getString(R.string.frontpageProgressTitleText), 
	    		getString(R.string.frontpageProgressBodyText), 
	    		true);
	    // We may have missed an initial few notifications during model setup, so explicitly update the 
	    // UI with data from the model to ensure that we are in sync
	    // In case the model is empty, update() just simply does nothing
	    update();
	}
		
	public void onNewsItemClicked(View newsItemView) {
		Log.d(FrontPageActivity.logTag, "News item clicked");
		Intent intent = new Intent(this, NewsItemDetailsActivity.class);
		String absId = (String)newsItemView.getTag(); // Tag is the absolute id as a string

		if (absId!=null) {
			intent.putExtra("infoObjectId", absId);
		} else {
			intent.putExtra("infoObjectId", "none");
			Log.w(FrontPageActivity.logTag, "No info object associated with view. This should never happen");
		}
		startActivity(intent);
	}

	public void onSearchButtonClick(View button) {
		onSearchButtonClick(button, false);
	}
	
	private void destroyProgressDialog() {
		if (progressDialog!=null) {
			progressDialog.dismiss();
		}
		progressDialog = null;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		return super.onOptionsItemSelected(item, false);
	}
	
	private void update() {
		update(null, null);
	}

	public void onPause() {
		super.onPause();
		destroyProgressDialog();
	}
	
	public void onStop() {
		super.onStop();
		destroyProgressDialog();
	}
	
	public void update(Observable observable, Object data) {
		Log.d(FrontPageActivity.logTag, "Received notification that info object list changed");
		
		List<InfoObject> ios = InfoGalleriModel.getInstance().getInfoObjects(InfoObject.TYPE_STANDARD);
		
		if (ios.size()<=0) {
			Log.d(FrontPageActivity.logTag, "Ignoring notification, as model is currently empty");
			return;
		}
		
		InfoObject topLeftIo = null;
		InfoObject topRightIo = null;
		InfoObject bottomLeftIo = null;
		InfoObject bottomRightIo = null;
		
		// Locate featured news items
		// Remove any featured news items found from ios so they are not shown in the
		// standard news list populated below
		for (InfoObject infoObject : new ArrayList<InfoObject>(ios)) {
			if (infoObject.hasCategory(getResources().getString(R.string.topLeftFeaturedNewsItemCategory))) {
				Log.d(FrontPageActivity.logTag, "Found top left featured news item");
				if (topLeftIo==null) {
					topLeftIo = infoObject;
					ios.remove(infoObject);
				}
			} else if (infoObject.hasCategory(getResources().getString(R.string.topRightFeaturedNewsItemCategory))) {
				Log.d(FrontPageActivity.logTag, "Found top right featured news item");
				if (topRightIo==null) {
					topRightIo = infoObject;
					ios.remove(infoObject);
				}
			} else if (infoObject.hasCategory(getResources().getString(R.string.bottomLeftFeaturedNewsItemCategory))) {
				Log.d(FrontPageActivity.logTag, "Found bottom left featured news item");
				if (bottomLeftIo==null) {
					bottomLeftIo = infoObject;
					ios.remove(infoObject);
				}
			} else if (infoObject.hasCategory(getResources().getString(R.string.bottomRightFeaturedNewsItemCategory))) {
				Log.d(FrontPageActivity.logTag, "Found bottom right featured news item");
				if (bottomRightIo==null) {
					bottomRightIo = infoObject;
					ios.remove(infoObject);
				}
			}
		}
		// No categorized featured news items,
		// so just grab whatever
		if (topLeftIo==null && ios.size()>0) {
			topLeftIo = ios.remove(0);
		}
		if (topRightIo==null && ios.size()>0) {
			topRightIo = ios.remove(0);
		}
		if (bottomLeftIo==null && ios.size()>0) {
			bottomLeftIo = ios.remove(0);
		}
		if (bottomRightIo==null && ios.size()>0) {
			bottomRightIo = ios.remove(0);
		}
		
		LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v = findViewById(R.id.bottomNewsLinearLayout);
		final LinearLayout bottomNewsLayout = (LinearLayout)v;
		Log.d(FrontPageActivity.logTag, "Removing all news views from bottom news layout");
		
		bottomNewsLayout.removeAllViews();
		

//		URL defaultImageUrl = null;
//		try {
//			defaultImageUrl = new URL("http://www.mediatehawaii.org/wp-content/uploads/placeholder-300x300.jpg");
//		} catch (MalformedURLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
				
		Bitmap defaultBitmap = ViewUtils.getNewsItemDefaultBitmap();

		if (topLeftIo!=null) {
			View newsItem = inflater.inflate(R.layout.featurednewsitem, null);
			
			String headlineHTML = topLeftIo.getHeadline(AppConfiguration.getInstance().getContentLanguage());
			Spanned headline = null;
			if (headlineHTML != null) {
				headline = Html.fromHtml(headlineHTML);
			}
			else {
				Log.w(FrontPageActivity.logTag, "No headline for given language found in infoobject.");
				headline = new SpannedString("");
			}
			newsItem.setTag(topLeftIo.getAbsoluteId().toString());
			TextView newsItemTextView = (TextView)newsItem.findViewById(R.id.featuredNewsItemTextView);			
			TextView newsItemTextView2 = (TextView)newsItem.findViewById(R.id.featuredNewsItemTextView2);			
			TextView newsItemTextView3 = (TextView)newsItem.findViewById(R.id.featuredNewsItemTextView3);			
			TextView newsItemTextView4 = (TextView)newsItem.findViewById(R.id.featuredNewsItemTextView4);			
			TextView newsItemTextView5 = (TextView)newsItem.findViewById(R.id.featuredNewsItemTextView5);			
			TextView newsItemTextView6 = (TextView)newsItem.findViewById(R.id.featuredNewsItemTextView6);			
	    	newsItemTextView.setText(headline);
	    	newsItemTextView2.setText(headline);
	    	newsItemTextView3.setText(headline);
	    	newsItemTextView4.setText(headline);
	    	newsItemTextView5.setText(headline);
	    	newsItemTextView6.setText(headline);
	    	ImageView newsItemBackgroundImageView  = (ImageView)newsItem.findViewById(R.id.featuredNewsItemBackgroundImageView);
	    	LinearLayout topLeftLinearLayout = (LinearLayout)findViewById(R.id.featuredNewsLinearLayoutTopLeft);
	    	Log.d(FrontPageActivity.logTag, "Replacing top left featured news item");
	    	topLeftLinearLayout.removeAllViews();
	    	topLeftLinearLayout.addView(newsItem);	    	
	    	Media firstImage = topLeftIo.getFirstImageMedia();
    		ImageCache.getInstance().loadImage(defaultBitmap, newsItemBackgroundImageView, null, UIUtils.getScreenWidth(), UIUtils.dipToPx(100));
	    	if (firstImage!=null) {
	    		ImageCache.getInstance().loadImage(firstImage.getUrl(), newsItemBackgroundImageView, null, UIUtils.getScreenWidth()/2, UIUtils.dipToPx(100));
	    	}	    	
		}
		
		if (topRightIo!=null) {
			View newsItem = inflater.inflate(R.layout.featurednewsitem, null);
			
			String headlineHTML = topRightIo.getHeadline(AppConfiguration.getInstance().getContentLanguage());
			Spanned headline = null;
			if (headlineHTML != null) {
				headline = Html.fromHtml(headlineHTML);
			}
			else {
				Log.w(FrontPageActivity.logTag, "No headline for given language found in infoobject.");
				headline = new SpannedString("");
			}
			
			newsItem.setTag(topRightIo.getAbsoluteId().toString());
			TextView newsItemTextView = (TextView)newsItem.findViewById(R.id.featuredNewsItemTextView);			
			TextView newsItemTextView2 = (TextView)newsItem.findViewById(R.id.featuredNewsItemTextView2);			
			TextView newsItemTextView3 = (TextView)newsItem.findViewById(R.id.featuredNewsItemTextView3);			
			TextView newsItemTextView4 = (TextView)newsItem.findViewById(R.id.featuredNewsItemTextView4);			
			TextView newsItemTextView5 = (TextView)newsItem.findViewById(R.id.featuredNewsItemTextView5);			
			TextView newsItemTextView6 = (TextView)newsItem.findViewById(R.id.featuredNewsItemTextView6);	    	
			newsItemTextView.setText(headline);
			newsItemTextView2.setText(headline);
			newsItemTextView3.setText(headline);
			newsItemTextView4.setText(headline);
			newsItemTextView5.setText(headline);
			newsItemTextView6.setText(headline);
	    	ImageView newsItemBackgroundImageView  = (ImageView)newsItem.findViewById(R.id.featuredNewsItemBackgroundImageView);
	    	LinearLayout topLeftLinearLayout = (LinearLayout)findViewById(R.id.featuredNewsLinearLayoutTopRight);
	    	Log.d(FrontPageActivity.logTag, "Replacing top right featured news item");
	    	topLeftLinearLayout.removeAllViews();
	    	topLeftLinearLayout.addView(newsItem);
	    	
	    	Media firstImage = topRightIo.getFirstImageMedia();
	    	ImageCache.getInstance().loadImage(defaultBitmap, newsItemBackgroundImageView, null, UIUtils.getScreenWidth()/2, UIUtils.dipToPx(100));
	    	if (firstImage!=null) {
	    		ImageCache.getInstance().loadImage(firstImage.getUrl(), newsItemBackgroundImageView, null, UIUtils.getScreenWidth()/2, UIUtils.dipToPx(100));
	    	}
		}
		
		if (bottomLeftIo!=null) {
			View newsItem = inflater.inflate(R.layout.featurednewsitem, null);
			
			String headlineHTML = bottomLeftIo.getHeadline(AppConfiguration.getInstance().getContentLanguage());
			Spanned headline = null;
			if (headlineHTML != null) {
				headline = Html.fromHtml(headlineHTML);
			}
			else {
				Log.w(FrontPageActivity.logTag, "No headline for given language found in infoobject.");
				headline = new SpannedString("");
			}
			
			newsItem.setTag(bottomLeftIo.getAbsoluteId().toString());
			TextView newsItemTextView = (TextView)newsItem.findViewById(R.id.featuredNewsItemTextView);			
			TextView newsItemTextView2 = (TextView)newsItem.findViewById(R.id.featuredNewsItemTextView2);			
			TextView newsItemTextView3 = (TextView)newsItem.findViewById(R.id.featuredNewsItemTextView3);			
			TextView newsItemTextView4 = (TextView)newsItem.findViewById(R.id.featuredNewsItemTextView4);			
			TextView newsItemTextView5 = (TextView)newsItem.findViewById(R.id.featuredNewsItemTextView5);			
			TextView newsItemTextView6 = (TextView)newsItem.findViewById(R.id.featuredNewsItemTextView6);
	    	newsItemTextView.setText(headline);
	    	newsItemTextView2.setText(headline);
	    	newsItemTextView3.setText(headline);
	    	newsItemTextView4.setText(headline);
	    	newsItemTextView5.setText(headline);
	    	newsItemTextView6.setText(headline);
	    	ImageView newsItemBackgroundImageView  = (ImageView)newsItem.findViewById(R.id.featuredNewsItemBackgroundImageView);
	    	LinearLayout topLeftLinearLayout = (LinearLayout)findViewById(R.id.featuredNewsLinearLayoutBottomLeft);
	    	Log.d(FrontPageActivity.logTag, "Replacing bottom left featured news item");
	    	topLeftLinearLayout.removeAllViews();
	    	topLeftLinearLayout.addView(newsItem);
	    	
	    	Media firstImage = bottomLeftIo.getFirstImageMedia();
    		ImageCache.getInstance().loadImage(defaultBitmap, newsItemBackgroundImageView, null, UIUtils.getScreenWidth()/2, UIUtils.dipToPx(100));
	    	if (firstImage!=null) {
	    		ImageCache.getInstance().loadImage(firstImage.getUrl(), newsItemBackgroundImageView, null, UIUtils.getScreenWidth()/2, UIUtils.dipToPx(100));
	    	}
		}

		
		if (bottomRightIo!=null) {
			View newsItem = inflater.inflate(R.layout.featurednewsitem, null);

			String headlineHTML = bottomRightIo.getHeadline(AppConfiguration.getInstance().getContentLanguage());
			Spanned headline = null;
			if (headlineHTML != null) {
				headline = Html.fromHtml(headlineHTML);
			}
			else {
				Log.w(FrontPageActivity.logTag, "No headline for given language found in infoobject.");
				headline = new SpannedString("");
			}
			
			newsItem.setTag(bottomRightIo.getAbsoluteId().toString());
			TextView newsItemTextView = (TextView)newsItem.findViewById(R.id.featuredNewsItemTextView);			
			TextView newsItemTextView2 = (TextView)newsItem.findViewById(R.id.featuredNewsItemTextView2);			
			TextView newsItemTextView3 = (TextView)newsItem.findViewById(R.id.featuredNewsItemTextView3);			
			TextView newsItemTextView4 = (TextView)newsItem.findViewById(R.id.featuredNewsItemTextView4);			
			TextView newsItemTextView5 = (TextView)newsItem.findViewById(R.id.featuredNewsItemTextView5);			
			TextView newsItemTextView6 = (TextView)newsItem.findViewById(R.id.featuredNewsItemTextView6);
	    	newsItemTextView.setText(headline);
	    	newsItemTextView2.setText(headline);
	    	newsItemTextView3.setText(headline);
	    	newsItemTextView4.setText(headline);
	    	newsItemTextView5.setText(headline);
	    	newsItemTextView6.setText(headline);
	    	ImageView newsItemBackgroundImageView  = (ImageView)newsItem.findViewById(R.id.featuredNewsItemBackgroundImageView);
	    	LinearLayout topLeftLinearLayout = (LinearLayout)findViewById(R.id.featuredNewsLinearLayoutBottomRight);
	    	Log.d(FrontPageActivity.logTag, "Replacing bottom right featured news item");
	    	topLeftLinearLayout.removeAllViews();
	    	topLeftLinearLayout.addView(newsItem);

	    	Media firstImage = bottomRightIo.getFirstImageMedia();
	    	ImageCache.getInstance().loadImage(defaultBitmap, newsItemBackgroundImageView, null, UIUtils.getScreenWidth()/2, UIUtils.dipToPx(UIUtils.dipToPx(100)));
	    	if (firstImage!=null) {
	    		ImageCache.getInstance().loadImage(firstImage.getUrl(), newsItemBackgroundImageView, null, UIUtils.getScreenWidth()/2, UIUtils.dipToPx(100));
	    	}
	    	
		}
		
		Bitmap gradientBmp = ViewUtils.getNewsItemGradientBitmap();
		
		for (InfoObject io : ios) {
			View newsItem = inflater.inflate(R.layout.newsitem, null);
			newsItem.setId(io.getAbsoluteId().hashCode());
			Media firstImage = io.getFirstImageMedia();
			newsItem.setTag(io);
			//viewToInfoObjectIdMap.put(newsItem.getId(), io.getAbsoluteId());
			View clickableView = newsItem.findViewById(R.id.newsItemLayout);
			clickableView.setTag(io.getAbsoluteId().toString());
	    	TextView newsItemTextView = (TextView)newsItem.findViewById(R.id.newsItemTextView);
	    	ImageView newsItemThumbnailImageView = (ImageView)newsItem.findViewById(R.id.newsItemThumbnailImageView);
	    	String headlineHTML = io.getHeadline(AppConfiguration.getInstance().getContentLanguage());
	    	if (headlineHTML != null) {
	    		newsItemTextView.setText(Html.fromHtml(headlineHTML));
	    	}
	    	else {
	    		newsItemTextView.setText("");
	    	}
			bottomNewsLayout.addView(newsItem);
			
//			Animation slideInAnimation = AnimationUtils.loadAnimation(this, R.anim.newsitem_fade_in);
//			slideInAnimation.setStartOffset(currentStartOffset+=200);
//			newsItem.startAnimation(slideInAnimation);
			
			Log.d(logTag, "ImageView size: " + newsItemThumbnailImageView.getWidth() + "x" + newsItemThumbnailImageView.getHeight());
			ImageCache.getInstance().loadImage(defaultBitmap, newsItemThumbnailImageView, gradientBmp, 75, 80);
		    if (firstImage!=null) {
	    		ImageCache.getInstance().loadImage(firstImage.getUrl(), newsItemThumbnailImageView, gradientBmp, 75, 80);
	    	}
		}
		
		View mainView = findViewById(R.id.frontpageNewsItemsLinearLayout);
    	AlphaAnimation alphaAnim = new AlphaAnimation(0, 1);
    	alphaAnim.setDuration(1000);
    	mainView.startAnimation(alphaAnim);
    	
    	destroyProgressDialog();

	}
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}
	
    protected void onDestroy() {
    	super.onDestroy();
    	// Stop the tracker when it is no longer needed.
    	//tracker.stopSession();
    }
}
